package com.hr;

import java.util.ArrayList;
import java.util.List;

import com.googlecode.cswish.exception.ApplicationException;

public class SeqTimeRange extends TimeRange {

	public SeqTimeRange(TimeRange tr) {
		super(tr.getTimeFrom(), tr.getTimeTo());
		this.setMarkAndType(tr.getMark(), tr.getType());
		safeChilds().add(tr);
	}
	
	public void addLastChild(TimeRange tr) {
		TimeRange lastTr = getLast();
		if (lastTr == null) {
			safeChilds().add(tr);
			
			setTimeFrom(tr.getTimeFrom());
			setTimeTo(tr.getTimeTo());
		} else {
			if (lastTr.getTimeToMinute() == tr.getTimeFromMinute()) {
				setTimeTo(tr.getTimeTo());
			} else {
				throw new ApplicationException("time range is not sequence");
			}

			if (tr instanceof SeqTimeRange) {
				SeqTimeRange trc = (SeqTimeRange) tr;
				safeChilds().addAll(trc.safeChilds());
			} else {
				safeChilds().add(tr);
			}
		}
	}
	
	public TimeRange getFirst() {
		return safeChilds().get(0);
	}
	
	public TimeRange getLast() {
		List<TimeRange> safeChilds = safeChilds();
		return safeChilds.get(safeChilds.size() - 1);
	}
	
	public List<TimeRange> safeChilds() {
		if (childs == null) {
			childs = new ArrayList<TimeRange>();
		}
		
		return childs;
	}
	
	private List<TimeRange> childs;
}
